;
(function (call) {
    var szyb = {
        mapId: "tjMap",
        selectedPro: [],
        playList: null,
        latestTime: null,
        isShowDataAnalysis: false,
        currentSelectEle: null,
        currentSelectTime: '', //当前选中的时间
        currentPro: null,
        router: {
            cfg: "/business/szyb/json/szyb.json",
            tccfg: "business/template/tc.html",
            gridData: 'sjyb/queryModelGridData',
			getSystemRecoJson:'dealData/getJsonData',
			getfjotsgrid:'/fjots/dmsRenewM4',
            gridDataPan:'sjyb/queryModelGridDataByPanGu',
			largeModelqueryModelGridData:'largeModel/queryModelGridData',
			// findRiseGridDataByElement: 'rise/findRiseGridDataByElement',
			queryGridDataFormRS: '/shortWarn/szms/queryGridDataFormRS', //rise使用新的接口
			queryGridDataFormRSMin: '/shortWarn/szms/queryGridDataFormRSMin', //rise使用新的接口
            getLatestTime: 'sjyb/queryModelGridDataLatestTime',
            initStampPath: "/business/template/stamp.html",
            initModelContrastPath: "/business/template/modelContrast.html",
            initLineProPop: "/business/template/linepro.html",
            initPointProPop: "/business/template/pointproV1.html",
            initProductPicPop: "/business/template/product-pic.html",
            initModelMapPath: "/business/template/modelmap.html",
            dealDataDownData: 'dealData/downData', //下载气象数据
            queryCmamesoGridData: '/sjyb/queryCmamesoGridData',
            queryDKJLZSGridData: '/sjyb/queryDKJLZSGridData', //低空急流指数
        },
        init: function () {
            var that = this;
            $.getJSON(that.router.cfg, function (cfg) {
                if (cfg) {
                    that.buildContainer(cfg);
                    that.bindEvt();
                }
            })
            // 点击任意点
            GIS.MouseEvent.showLatLon(that.mapId, function (location) {
                $("#lat").text(location.lat);
                $("#lon").text(location.lon);
            }, null, function (location) {
                if (that.isShowDataAnalysis && $(".cafe-busis-toolsbar-left #szyb").hasClass("active")) {
                    window.analysis = {
                        "stationId": "",
                        "type": "1h",
                        "currentTime": $(".product-szyb-datepicker #date").IDatePicker().getVal() + ':00',
                        "stationName": "",
                        "stationLon": location.lon,
                        "stationLat": location.lat
                    };
                    CafeJS.tqfx.showDateAnalysis("dateAnalysis");
                }
            });
        },
        // 获取最新起报时间
        getLatestTime: function (call) {
            var that = this;
            var modeType = $(".product-szyb-tab li.active").data('model').fullname;
            var param = {
                modeType: modeType
            };
            if($("#userInfo").data("isMatchuser")){
                that.latestTime = "2022-07-26 08:00:00";
				if(modeType == "GRAPES" || modeType == "EC"){
					that.latestTime = "2022-07-25 20:00:00";
				}
				if (call)
				call();
                return;
            }
            if("Pangu-ART" == param.modeType){
                //早上6点前前天20 。6点到18点昨天08 18点后昨天20.format('yyyy-MM-dd hh:mm:00')
                let hours = new Date().getHours();
                if(hours<5 || (hours == 5 && new Date().getMinutes()<30)){
                    //前天20
                    const currentDate = new Date();
                    currentDate.setDate(currentDate.getDate() - 2);
                    that.latestTime = new Date(currentDate).format('yyyy-MM-dd 20:00:00')
                }else if((hours>=6 && hours<17) || (hours==5&& new Date().getMinutes()>=30)|| (hours==17&& new Date().getMinutes()<30)){
                    //昨天08
                    const currentDate = new Date();
                    currentDate.setDate(currentDate.getDate() - 1);
                    that.latestTime = new Date(currentDate).format('yyyy-MM-dd 08:00:00')
                }else{
                    //昨天20
                    const currentDate = new Date();
                    currentDate.setDate(currentDate.getDate() - 1);
                    that.latestTime = new Date(currentDate).format('yyyy-MM-dd 20:00:00')
                }
                if (call)
                    call();
            }if("风清" == param.modeType){
                let hours = new Date().getHours();
                if(hours<6){
					//昨天08
                    const currentDate = new Date();
                    currentDate.setDate(currentDate.getDate() - 1);
                    that.latestTime = new Date(currentDate).format('yyyy-MM-dd 08:00:00')
                }else if(hours>=6 && hours<18){
                    //昨天20
                    const currentDate = new Date();
					currentDate.setDate(currentDate.getDate() - 1);
                    that.latestTime = new Date(currentDate).format('yyyy-MM-dd 20:00:00')
                }else{
                    //今天08
                    const currentDate = new Date();
                    that.latestTime = new Date(currentDate).format('yyyy-MM-dd 08:00:00')
                }
                if (call)
                    call();
            }else if("rise" == param.modeType){
                let currentDate = new Date(new Date().getTime() - 1000*60*60);
                that.latestTime = new Date(currentDate).format('yyyy-MM-dd hh:00:00');
				 if (call)
                    call();
			} else if(param.modeType === 'CMA-MESO6'){
                let currentDate = new Date().getTime() - 1000 * 60 * 60 * 6;
                let hours = new Date(currentDate).getHours();
                let hourList = [2, 5, 8, 11, 14, 17, 20, 23];
                if (!hourList.includes(hours)) {
                    let index = hourList.findIndex(el => el > hours);
                    hours = hourList[index - 1];
                }
                that.latestTime = new Date(new Date(currentDate).setHours(hours, 0, 0, 0)).format('yyyy-MM-dd hh:00:00');
				 if (call)
                    call();
			}
            else{
                 $.ajax({
                    url: this.router.getLatestTime,
                    type: 'GET',
                    dataType: 'json',
                    data: param,
                }).done(function (res) {
                    if (res.isSuccess)
                        that.latestTime = res.data;
                    if (call)
                        call();
                })
            }
           
        },
        /**
         * 构建弹出框内容
         */
        buildContainer: function (data) {
            var that = this;
            if (!data) {
                return;
            }
            if (data.pro_type.global) {
                that.buildModel(data, data.pro_type.global, "全球模式：")
            }

            if (data.pro_type.area) {
                that.buildModel(data, data.pro_type.area, "区域模式：")
            }
			if (data.pro_type.hundred) {
                that.buildModel(data, data.pro_type.hundred, "百米模式：")
            }
            that.buildModelContrast("模式对比")
            $(".product-szyb-tab").show();
        },
        buildModelContrast(text) {
            var that = this;
            var $div = $('<div></div>');
            var $span = $('<span class="szyb-model-contrast">' + text + '</span>');
            $div.append($span);
            $(".product-szyb-tab").append($div);
            $span.off("click").on("click", function () {
                that.initModelContrast($(this));
            });
            var $span1 = $('<span class="szyb-model-contrast">时序分析</span>');
            $div.append($span1);
            $span1.off("click").on("click", function () {
                that.isShowDataAnalysis = !that.isShowDataAnalysis;
                $(this).toggleClass("isShowDataAnysis");
                if (that.isShowDataAnalysis && $(".cafe-busis-toolsbar-left #szyb").hasClass("active")) {
                    window.analysis = {
                        "stationId": "",
                        "type": "1h",
                        "currentTime": $(".product-szyb-datepicker #date").IDatePicker().getVal() + ':00',
                        "stationName": "",
                        // "stationLon":location.lon,
                        // "stationLat":location.lat
                    };
                    CafeJS.tqfx.showDateAnalysis("dateAnalysis");
                } else {
                    CafeJS.ModalBoxClose("dateAnalysis");
                }
            });
        },
        //构建模式
        buildModel: function (data, selfData, text) {
            var that = this;
            var $div = $('<div></div>');
            var $span = $('<span>' + text + '</span>');
            $div.append($span);
            var $childDiv = $('<div></div>');
            $div.append($childDiv);
            var $ul = $('<ul></ul>');
            selfData.forEach(function (item) {
                var $li = $(`<li>${item.name}</li>`);
                $li.data('model', item);
                $li.off().click(function () {
                    if ($(this).hasClass("active")) {
                        return;
                    }
                    that.delAllLayer(); //切换模式后, 清空之前模式数据
                    $(".product-szyb-tab li").removeClass("active");
                    $(this).addClass("active");

                    $('.product-szyb-datepicker').empty()
                        .append(`
						<div class="date-panel">
							<input class="DateAgent" id="date" data-options="${item.dateOptions}" value="">
							<i class="btn-forward"></i>
							<i class="btn-backward"></i>
							<i class="btn-newest"></i>
						</div>`);
                    $.IDate(".product-szyb-datepicker .date-panel", {
                        query: function query() {
                            szyb.buildLastTime(function () {
                                szyb.getMultiGridData();
                            });
                            if ($("#modal_product_pic").length > 0) {
                                productPic.initProduct(0);
                            }
                        }
                    });
                    that.getLatestTime(function () {
                        if (that.latestTime) {
                            $(".product-szyb-datepicker #date").IDatePicker().setVal(that.latestTime);
                            that.buildLastTime();
                        }
                        $(".product-szyb-list").find('li.default').trigger('click');
                    });
                    that.buildLastTime();
                    that.buildProContent(data.basic_pro[item.id] || []);
                })
                $ul.append($li);
            })
            $childDiv.append($ul);
            $(".product-szyb-tab").append($div);
        },
        /**
         * 构建要素展示
         * data 要素列表
         */
        buildProContent: function (data) {
            var that = this;
            $(".product-szyb-list").empty();
            data.forEach(function (item) {
                var $item = $('<div>').addClass('product-item');

                var $title = $('<div>').addClass('product-title');
                $title.data('type', item.group_id);
                $title.html(item.group_name);

                if (item.checkbox) {
                    $title.append(`<div class="product-correlated"><input type=checkbox ${item.checkbox.checked ? "checked" : ""}>${item.checkbox.name}</div>`);
                }

                //添加下载按钮
                if (item.download) {
                    $title.append(`<div class="product-szyb-download">${item.download.text}</div>`);
                }

                $item.append($title);
                if (item.content) {
                    if (!item.height) {
                        var $ul = $('<ul>');
                        if (item.group_id == 'custom') {
                            $ul = $('<ul>').addClass('product-pic-tab')
                        }
                        item.content.forEach(function (pro) {
                            let $span = $(`<span>${pro.ele_name}</span>`);
                            let $li = null;

                            if (pro.optionId) {
                                let $select = $(`<select id=${pro.optionId} style="margin-left: 10px;"></div>`).off('click').on('click', function (e) {
                                    e.stopPropagation();
                                }).change(function() {
                                    that.currentSelectTime = $(this).val();
                                    that.queryGridDataFormRS();
                                });
                                $select.append('<option value="" disabled selected>请选择</option>');
                                $li = $(`<li style="display: flex;"></li>`).append($span).append($select);
                            } else {
                                $li = $(`<li></li>`).append($span);
                            }

                            if (pro.selected)
                                $li.addClass("default");
                            if (item.maxHour)
                                pro.maxHour = item.maxHour; 
                            $li.data('pro', pro);
                            if (pro.title)
                                $li.attr('title', pro.title);
                            if (pro.width)
                                $li.css("width", pro.width);
                            $ul.append($li);
                        })
                        $item.append($ul);
                    } else {
                        var $table = $('<table>');
                        if (item.group_id == 'custom') {
                            $table.addClass('product-pic-tab')
                        }
                        var $thead = $('<tr>');
                        $thead.append('<th></th>');
						let heightData = item.height
						if(heightData &&item.heightLabel){
							heightData = item.heightLabel
						}
                        heightData.forEach(function (h) {
                            $thead.append(`<th>${h}</th>`);
                        })
                        $table.append($thead);
                        item.content.forEach(function (pro) {
                            var $tr = $('<tr>');
                            $tr.append(`<td>${pro.ele_name}</td>`);
                            item.height.forEach(function (h) {
                                var $td = $('<td>');
                                var newPro = $.extend({}, pro);
                                if (newPro.heights && -1 == $.inArray(h, newPro.heights)) {
                                    $td.addClass("disabled");
                                }
                                newPro.height = h;
                                newPro.interval = item.interval;
                                newPro.type = item.group_id;
                                $td.data('pro', newPro).attr('id', newPro.ele_id + h);
                                $tr.append($td);
                            })
                            $table.append($tr);
                        })
                        $item.append($table);
                    }
                }
                $(".product-szyb-list").append($item);
            })
        },
        // 初始化最近起报时间
        buildLastTime: function (call) {
            var interval = $(".product-szyb-tab li.active").data("model").interval;
            var baseDate = $(".product-szyb-datepicker #date").IDatePicker().getVal() + ":00";
            var newDate = new Date(baseDate);
            var liArr = [];
            for (var i = 0; i < 4; i++) {
                liArr.push(`<li class="${i == 0 ? 'active' : ''}" data-time="${newDate}">${newDate.format("ddhh")}</li>`);
                newDate.setHours(newDate.getHours() - interval);
            }
            $(".product-szyb-datechange ul").empty().append(liArr.reverse().join(""));

            if (call && this.playList) {
                let modeType = $(".product-szyb-tab li.active").data('model').fullname;
                let params = {
                    curDate: baseDate
                };

                if (modeType === 'CMA-MESO6') {
                    params.maxHour = [8, 20].includes(new Date(baseDate).getHours()) ? 72 : 36;
                    params.interval = 1;
                }

                this.playList.init(params);
                if ($.isFunction(call))
                    call();
            }
        },
        // 初始化播放列表
        initPlayList: function (pro) {
            var that = this;
            var startTime = pro.time;
			if(pro.ele.isrise && pro.ele.isrise == "true"){
				startTime = new Date(new Date(pro.time).getTime()+1000*60*60).format("yyyy-MM-dd hh:00:00")
			}
			if(pro.ele.isfjots && pro.ele.isfjots == "true"){
				startTime = new Date(new Date(pro.time).getTime()+1000*60*60*Number(pro.ele.interval)).format("yyyy-MM-dd hh:00:00")
			}

            var layers = that.getModels(pro.ele);
            var interval = pro.ele.interval * 60;
            this.playList = CafeJS.Timeline2({
                appendTo: "#a-m-timeline",
                curDate: startTime,
                type: 1,
                maxHour: pro.ele.maxHour || 240,
                pro: pro,
                dateOpt: {
                    dateFmt: 'yyyy-MM-dd hh',
                    timeInterval: 12,
                    customHm: [8, 20]
                },
                timeInterval: interval,
                layers: layers,
                gisId: that.mapId,
                call: function (pro) {
                    pro.forecastTime = that.playList.getCurTime();
                    CafeJS.layerManage.updateLayer(pro);

                    that.getModelGridData(pro);
                },
                getPlayData: function (pro, timeArr) {
                    that.getModelGridData(pro, timeArr);
                }
            });
            pro.forecastTime = that.playList.getCurTime();
            if (CafeJS.layerManage)
                CafeJS.layerManage.updateLayer(pro);
        },
        // 初始化图例
        initLegentpicker: function (ele, appendTo) {
            var that = this;
            var layers = that.getModels(ele);
            var layerIds = [], colorId = ele.color_id;
            $.each(layers, function (i, m) {
                layerIds.push(m.id);
            });
            if (ele.height && ele.height > 0 && colorId != 'SHIBIE')
                colorId += '_' + ele.height;
            CafeJS.legentPicker = CafeJS.Legentpicker({
                appendTo: appendTo,
                gisId: that.mapId,
                layerId: layerIds,
                totalWidth: 400,
                h_legend: 15,
                seq: 'decrease',
                productId: colorId,
                isShowSlider: true
            });
        },
        // 获取选中的要素格点数据
        getMultiGridData: function () {
            var that = this;
            if (this.selectedPro.length === 0) return;
            this.selectedPro.forEach(function (pro) {
                var proInfo = that.getProInfo(pro);
                that.getModelGridData(proInfo);
            })
            var forecastTime = that.playList.getCurTime();
            var time = $(".product-szyb-datepicker #date").IDatePicker().getVal() + ":00";
            CafeJS.layerManage.updateLayerTime(time, 'szyb', forecastTime);
        },
        getModelGridData: function (proInfo, timeArr) {
            var that = this;
			if (!proInfo) return;
			//天气识别
			if(proInfo.ele.type == "shibie" && proInfo.ele.data_type){
				that.getSystemRecoJsonfun(proInfo,timeArr);
				return;
			}
            GIS.LayerControll.showControll(this.mapId, ["dem", "seadem"], true);
            var pro = proInfo.ele;
            var element = pro.ele_id;
            var dataType = pro.data_type;
            dataType = dataType ? dataType : 'nc';

            var queryTime = that.playList.getCurTime() + ":00";
            var qbTime = new Date(proInfo.time).format('yyyy-MM-dd hh:mm:00');
            var agings = [],
                aging;
            if (timeArr) {
                timeArr.split(',').forEach(function (i) {
                    aging = (new Date(i).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                    aging = (Array(3).join('0') + aging).slice(-3);
                    agings.push(aging);
                })
                agings = agings.join(',');
            } else {
                agings = (new Date(queryTime).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                agings = (Array(3).join('0') + agings).slice(-3);
            }

            var modeType = $(".product-szyb-tab li.active").data().model.fullname;

            let url = that.router.gridData;
            var params = {
                queryTime: qbTime,
                modeType: modeType,
                period: agings,
                element: element == 'EDA2' ? 'EDA' : element,
                dataType: dataType
            }
            if (pro.interval)
                params.interval = pro.interval;
            if (pro.height)
                params.height = pro.height;
            if (!loading.isExist())
                loading.add();
			
			if (modeType === 'rise') {
                console.log('rise======>', that.selectedPro);
                // url = that.router.findRiseGridDataByElement;
                // params = {
				// 	fcstTime: qbTime,
				// 	index: agings,
				// 	element: element
				// }
                // url = that.router.queryGridDataFormRS;
                
				// params = {
				// 	element: element === 'tsfc' ? 'T2M' : element === 'usfc' ? 'WIND10M' : 'TP1H', //要素(2m气温：T2M，1小时累积降水：TP1H，地面风场：WIND10M)
                //     foreTime: new Date(proInfo.time).format('yyyyMMddhhmm00'), //预报时间(北京时，格式：yyyyMMddHHmmss)
                //     height: 0, //高度层(单位：米， 地面要素默认0)       
				// 	period: agings //时效:001~024
				// }

                params = {
					element: element === 'tsfc' ? 'T2M' : element === 'usfc' ? 'WIND10M' : 'TP1H', //要素(2m气温：T2M，1小时累积降水：TP1H，地面风场：WIND10M)
                    foreTime: new Date(proInfo.time).format('yyyyMMddhhmm00'), //预报时间(北京时，格式：yyyyMMddHHmmss)
                    height: 0, //高度层(单位：米， 地面要素默认0)       
					period: agings, //时效:001~024
                    selectId: that.selectedPro[0].optionId
				}

                that.currentSelectEle = params;
                that.currentPro = pro;
                that.queryGridDataFormRSMin(params);
                return;
			}

			if(modeType == "FJOTS"){
				url = that.router.getfjotsgrid;
				params = {
					fcstTime: new Date(proInfo.time).format('yyyyMMddhhmm00'),
					index: Number(agings),
					element: element
				}
			}
            if(modeType == "Pangu-ART"){
                url = that.router.gridDataPan;
                params = {
                    queryTime: qbTime,
                    modeType: pro.modeType?pro.modeType:modeType,
                    element: element,
                    period: Number(agings),
                    dataType: dataType
                }
                if (pro.interval)
                params.interval = pro.interval;
                if (pro.height)
                    params.height = pro.height;
            }
			if(modeType == "风清"){
				url = that.router.largeModelqueryModelGridData;
				params = {
                    queryTime: new Date(proInfo.time).format('yyyyMMddhh0000'),
                    modeType: pro.modeType,
                    element: element,
                    period: Number(agings),
					height:pro.height?pro.height:0
                }
			}

            if (modeType === 'CMA-MESO6'){
				url = that.router.queryCmamesoGridData;
				params = {
                    queryTime: new Date(proInfo.time).format('yyyyMMddhh0000'),
                    element: element,
                    aging: `${Number(agings)}`.padStart(2, '0'),
                }
			}

            if (element === 'lowLevelJet'){
				url = that.router.queryDKJLZSGridData;
				params = {
                    queryTime: new Date(proInfo.time).format('yyyyMMddhh0000'),
                    period: `${Number(agings)}`.padStart(3, '0'),
                }
			}
            
            CafeJS.ajax({
                url:url ,
                params: params,
                type: "GET",
                success: function (e) {
                    loading.remove();
                    var arrayBuffer = e.response;
                    console.log('arrayBuffer======>', arrayBuffer);
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(pro);
                        return;
                    }
                    console.log('ParseRaw======>', G.ParseRaw(arrayBuffer));
                    that.drawGridRawMap(arrayBuffer, pro);
                },
                error: function (e) {
                    loading.remove();
                    console.error(e);
                }
            })
        },
        // 绘制格点色斑图
        drawGridRawMap: function (data, pro) {
            var that = this;
            var typeArr = this.getModels(pro);
            var ele_id = pro.ele_id;
            var color_id = pro.color_id;
            if (pro.height && pro.data_type != 'txt') {
                GIS.LayerControll.showControll(this.mapId, ["dem", "seadem"], false);
                color_id = color_id + "_" + pro.height;
            }
            var legentCfg = CafeJS.Legentconfig().cfg();
            var colorObj = legentCfg[color_id];
            if (typeof colorObj === "undefined") {
                legentCfg[pro.color_id];
            }
            if (pro.models == 'isoline') {
				var rangeObj = G.ParseRaw(data).rangeObj, dval = 0.2;
                gridUtil.createIsoline(data, typeArr[0].id, colorObj.levels, [[
					[rangeObj.xmin + dval,rangeObj.ymax - dval],[rangeObj.xmax - dval,rangeObj.ymax - dval],[rangeObj.xmax - dval,rangeObj.ymin + dval],[rangeObj.xmin + dval,rangeObj.ymin + dval],[rangeObj.xmin + dval,rangeObj.ymax - dval]
				]]);
            } else {
                // 显示色斑和数值
                // GIS.GridShow.showGrid(this.mapId, typeArr, data, {}, colorObj);
                // GIS.GridShow.showGrid_rectify(this.mapId, typeArr, data, {}, colorObj);
                GIS.GridShow.showByTypes_raw(this.mapId, typeArr, data, {}, colorObj);
            }
            var min = ele_id.indexOf('TP') != -1 || ele_id.indexOf('RAIN') != -1 ? 0.1 : null;
            if(['HGT', 'PRMSL', 'PRMSLPAN', 'SFPRES'].indexOf(color_id) == -1){
                 CafeJS.legentPicker.updateLegentRange(typeArr, that.mapId, min);
            }
        },
        //获取要素样式
        getModels: function (pro) {
            var models = [];
            $.each(pro.models.split(","), function (i, m) {
                var layerId = "szyb-layer-" + m + "-" + pro.ele_id;
                if (pro.height) {
                    layerId = layerId + pro.height;
                }
                models.push({
                    type: m,
                    visible: true,
                    uv: false,
                    wd: true,
                    cacheConfig: 'noCache',
                    id: layerId
                });
            });
            return models;
        },
        // 增加产品图层
        addLayerManage: function (proInfo) {
            var that = this;
            if (CafeJS.layerManage) {
                CafeJS.layerManage.addLayer(proInfo);
            } else {
                CafeJS.layerManage = CafeJS.LayerManage({
                    appendTo: "#c-b-layermanage",
                    mapId: that.mapId,
                    proInfo: proInfo,
                    call: function (pro) {
                        CafeJS[pro.bussitype].initPlayList(pro);
                    },
                    close: function (pro) {
                        CafeJS[pro.bussitype].delLayer(pro);
                    }
                })
            }
            if (proInfo.isGrid && !proInfo.ele.frames && ['HGT', 'PRMSL', 'PRMSLPAN', 'SFPRES'].indexOf(proInfo.ele.color_id) == -1) {
                that.initLegentpicker(proInfo.ele, '.cafe-layer-item.active');
            }
        },
        // 删除图层后取消要素选择
        delLayer: function (pro) {
            var eleid = pro.ele.ele_id;
			debugger;
            if (pro.isGrid) {
                $(".product-szyb-list li.active").each(function () {
                    if ($(this).data('pro').ele_id == eleid) {
                        $(this).click();
                        return false;
                    }
                })

                $(".product-szyb-list td.active").each(function () {
                    if ($(this).data('pro').ele_id == eleid) {
                        $(this).click();
                        return false;
                    }
                })
            }
        },
        // 删除该模式所有的要素数据
        delAllLayer: function () {
            $(".product-szyb-list li.active,.product-szyb-list td.active").each(function () {
                $(this).click();
            })
            $("#modal_product_pic").remove();
        },
        // 移除当前要素的图层
        removeLayer: function (ele) {
            var proInfo = this.getProInfo(ele);
            CafeJS.layerManage.removeLayer(proInfo);
        },
        getProInfo: function (ele) {
            var height = ele.height != undefined ? ele.height : '';
            var name = $('.product-szyb-tab li.active').data('model').name;
            name += '_' + height + ele.ele_name;
            var time = $(".product-szyb-datepicker #date").IDatePicker().getVal() + ':00';
            var proInfo = {
                name: name,
                time: time,
                bussitype: 'szyb',
                ele: ele,
                isGrid: true,
                isSK: false
            }
            return proInfo;
        },
        // 清除格点图层
        clearGridLayer: function (proInfo) {
            var ele_id = proInfo.ele_id;
            if (proInfo.height) {
                ele_id = ele_id + proInfo.height;
            }
            var layerIds = [];
            if (!ele_id) return;
            GLMap.layerIds.forEach(function (layerId) {
                if (layerId.indexOf('szyb-layer') != -1 && layerId.indexOf(ele_id) != -1) {
                    layerIds.push(layerId);
                }
            })
            GIS.LayerControll.deleteLayer(this.mapId, layerIds);
        },
        // 线剖选择
        linesSelect: function () {
            var layerId = "linesSelect";
            var paths = [], points = [];
            GLMap.off(szyb.mapClick);
            GLMap.off(szyb.mousemove);
            GLMap.off(szyb.dblclick);
			debugger
            szyb.mapClick = GLMap.on("click", function (e) {
                var len = points.length;
                if (len > 0) {
                    var lastPoint = points[len - 1];
                    paths.push([[lastPoint.lon, lastPoint.lat], [e.mapX, e.mapY]]);

                    if (lastPoint.lon != e.mapX || lastPoint.lat != e.mapY) {
                        points.push({ lon: e.mapX, lat: e.mapY });
                    }
                } else {
                    points.push({ lon: e.mapX, lat: e.mapY });
                }
            });
            szyb.mousemove = GLMap.on("mousemove", function (e) {
                var len = points.length;
                if (len > 0) {
                    var lastPoint = points[len - 1];
                    var showPaths = [];
                    paths.forEach(function (value) { showPaths.push(value) });
                    showPaths.push([[lastPoint.lon, lastPoint.lat], [e.mapX, e.mapY]]);

                    GIS.LayerControll.deleteLayer(szyb.mapId, layerId);
                    var data = [{ paths: showPaths }];
                    GIS.Graphic.showPolyline(szyb.mapId, layerId, data, { style: { lineWidth: 1, strokeStyle: "rgb(255,0,0)" } });
                }
            });
            szyb.dblclick = GLMap.on("dblclick", function (e) {
				debugger
                GIS.LayerControll.deleteLayer(szyb.mapId, layerId);
                szyb.initLinePop(points);
                paths = [], points = [];
            });
        },
        // 点选
        pointSelect: function () {
            GLMap.off(szyb.mapClick);
            GLMap.off(szyb.mousemove);
            GLMap.off(szyb.dblclick);
            szyb.mapClick = GLMap.on("click", function (e) {
                //保留三位小数
                // callback(parseFloat(e.mapX).toFixed(3), parseFloat(e.mapY).toFixed(3));
                szyb.initPointPop(parseFloat(e.mapX).toFixed(3), parseFloat(e.mapY).toFixed(3));
            });
        },
        // 线剖弹框
        initLinePop: function (points) {
            var that = this;
            $("#modal_product_pic,#modal_modelMap,#modal_point_pro,#modal_line_pro,#modal_stamp").remove();
            CafeJS.ModalBox({
                id: 'line_pro',
                container: 'cafe-busis-container',
                title: "空间剖面",
                width: 1060,
                height: 740,
                m_top: 55,
                m_left: 520,
                hide: true,
                isBackdrop: false,
                url: that.router.initLineProPop,
                closed: function () {
                    GLMap.off(szyb.mapClick);
                    GLMap.off(szyb.mousemove);
                    GLMap.off(szyb.dblclick);
                    $(".product-szyb-list li").removeClass('active');
                    $("#modal_line_pro").remove();
                }
            });
            var time = $(".product-szyb-datepicker #date").IDatePicker().getVal();
            $("#modal_line_pro").data({
                'points': points,
                'time': time
            })
        },
        // 点剖弹框
        initPointPop: function (x, y) {
            var that = this;
            $("#modal_product_pic,#modal_modelMap,#modal_point_pro,#modal_line_pro,#modal_stamp").remove();
            CafeJS.ModalBox({
                id: 'point_pro',
                container: 'cafe-busis-container',
                title: "单站剖面",
                width: 912,
                height: 784,
                m_top: 55,
                m_left: 520,
                hide: true,
                isBackdrop: false,
                url: szyb.router.initPointProPop,
                closed: function () {
                    GLMap.off(szyb.mapClick);
                    $("#modal_point_pro").remove();
                    $(".product-szyb-list li").removeClass('active');
                }
            });
            var time = $(".product-szyb-datepicker #date").IDatePicker().getVal();
            $("#modal_point_pro").data({
                'x': x,
                'y': y,
                'time': time
            })
        },
        // 初始化产品图
        initProductPic: function () {
            szyb.initPicPop();
        },
        initPicPop: function () {
            var that = this;
            $("#modal_product_pic,#modal_modelMap,#modal_point_pro,#modal_line_pro,#modal_stamp").remove();
            CafeJS.ModalBox({
                id: 'product_pic',
                container: 'cafe-busis-container',
                title: "产品图",
                width: 1200,
                height: 840,
                m_top: 55,
                m_left: 530,
                hide: true,
                url: that.router.initProductPicPop,
                closed: function () {
                    $("#modal_product_pic").remove();
                    $(".product-pic-tab li").removeClass('active');
                    $(".product-pic-tab td").removeClass('active');
                }
            });
        },
        relatedPro: function (pro, isSelected) { // 关联系统识别
            var isRelated = $(".product-correlated input:checked").length > 0;
            if (isRelated && pro.type == 'height') {
                var relatedProArr = pro.related[pro.height];
                if (!relatedProArr || relatedProArr.length === 0) return;
                relatedProArr.forEach(function (proId) {
                    var $item = $("#" + proId + pro.height);
                    if (isSelected) {
                        if (!$item.hasClass('active'))
                            $item.click();
                    } else {
                        if ($item.hasClass('active'))
                            $item.click();
                    }
                })
            }
        },
        //系统识别-下载
		dealDataDownDataFun: function() {
            console.log('this.playList==================>, ', this.playList);
            var that = this;
            var datePickerTime = $(".product-szyb-datepicker #date").IDatePicker().getVal() + ':00'; //2024-10-23 08' + ':00'
            var playTime = this.playList ? this.playList.getCurTime() : datePickerTime;
            var timeDifference = (new Date(playTime).getTime() - new Date(datePickerTime).getTime()) / 1000 / 60 / 60;
            console.log('datePickerTime: ', datePickerTime, ', playTime: ', playTime, ', timeDifference: ', timeDifference);
            var time = new Date(datePickerTime).format('yyyyMMddhh'); //2024102308
            var hour = timeDifference.toString().padStart(3, '0'); //002

            var data = {
                modeType: 'EC',
                // weatherType: '',
                high: '500',
                time: time,
                hour: hour,
                type: 'feature'
            }
            
            CafeJS.ajax({
				url: this.router.dealDataDownData,
				type: 'GET',
				params: data,
                success: function (e) {
                    console.log('e===================>, ', e);
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        return;
                    }
                    that.downloadArrayBufferFun(arrayBuffer, `${time}.${hour}`);
                }
			});
		},
        //下载arrayBuffer文件
        downloadArrayBufferFun: function(arrayBuffer, fileName) {
            var blob = new Blob([arrayBuffer]);
            var elink = document.createElement('a');
            elink.download = fileName;
            elink.href = window.URL.createObjectURL(blob);
            elink.style.display = 'none';
            document.body.appendChild(elink);
            elink.click();
            document.body.removeChild(elink);
            window.URL.revokeObjectURL(blob);
        },
		//查询天气识别数据
		getSystemRecoJsonfun:function(proInfo,timeArr){
			var that = this;
			var queryTime = that.playList.getCurTime() + ":00";
            var qbTime = new Date(proInfo.time).format('yyyy-MM-dd hh:00:00');
			debugger;
			console.log("getSystemRecoJsonfun");
            var agings = [],aging;
            if (timeArr) {
                timeArr.split(',').forEach(function (i) {
                    aging = (new Date(i).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                    aging = (Array(3).join('0') + aging).slice(-3);
                    agings.push(aging);
                })
                agings = agings.join(',');
            } else {
                agings = (new Date(queryTime).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                agings = (Array(3).join('0') + agings).slice(-3);
            }
			var pro = proInfo.ele;
            var element = pro.ele_id;
			 if (!loading.isExist())
              loading.add();
			$.ajax({
				url: this.router.getSystemRecoJson,
				type: 'GET',
				dataType: 'json',
				data:{
					modeType:"EC",
					weatherType:element,
					high:pro.height,
					time:new Date(proInfo.time).format('yyyyMMddhh'),
					hour:agings
				}
			}).done(function (res) {
				let layerId = "szyb-layer-"+element+pro.height;
				GIS.LayerControll.deleteLayer("tjMap", layerId);
				loading.remove();
				let optionstyle = {
					"trough":{
						lineWidth: 5,
						strokeStyle: "rgba(255,0,0,1)"
					},
					"jet":{
						lineWidth: 5,
						strokeStyle: "rgba(255,0,0,1)"
					},
					"default":{
						lineWidth: 1,
						strokeStyle: "rgba(255,0,0,1)"
					}
				}
				if(res.code == 200 && res.data){
					let data = JSON.parse(res.data);
					if(pro.data_type == "txt"){
						let option = [];
						Object.values(data.features).forEach((item) => {
							option.push({
								value: Number(item.center.value).toFixed(1),
								lon: item.center.lon,
								lat: item.center.lat,
								options: {
								  labelStyle: {
									//family: "cursive",
									size: 14,
									fillStyle: "rgba(255,0,0,1)",
									textAlign: "center",
								  },
								  bgStyle: {
								  },
								},
							});
						});
						GIS.Station.showLabel("tjMap",layerId, option, {zIndex: 99});
					}else if(pro.data_type == "line"){
						let option = [];
						Object.values(data.features).forEach((item) => {
							option.push(item.axes.point);
						});
						GIS.Graphic.showPolyline("tjMap", layerId, [{ paths: option}], {
							style: optionstyle[element]?optionstyle[element]:optionstyle["default"],
							type: "canvas",
						})
					}else if(pro.data_type == "doubleline"){
						let option = [];
						Object.values(data.features).forEach((item) => {
							option.push(item.axes.point);
						});
						GIS.Graphic.showDoublePolyline("tjMap", layerId, [{ paths: option}], {
							style: optionstyle[element]?optionstyle[element]:optionstyle["default"],
							type: "canvas",
						})
					}else{
						let option = [];
						Object.values(data.features).forEach((item) => {
							option.push(item.axes.point);
						});
						GIS.Graphic.showPolylineArrow("tjMap", layerId, [{ paths: option}], {
							style: optionstyle[element]?optionstyle[element]:optionstyle["default"],
							type: "canvas",
						})
					}
					
				}else{
					alert("该时间点没有数据");
				}
				console.dir(res.data);
			})
		},
        /**
         * 绑定事件操作
         */
        bindEvt: function () {
            var that = this;
            // 要素点击事件
            $(".product-szyb-list").off('click').on('click', 'li', function () {
                $(".isShowDataAnysis").removeClass('isShowDataAnysis');
                that.isShowDataAnalysis = false;
                var pro = $(this).data('pro');
                $("#modal_" + pro.ele_id).remove();
                $("#modal_" + pro.ele_id + '_pro').remove();
                $("#modal_product_pic").remove();
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");

                    that.selectedPro = that.selectedPro.filter(item => item.ele_id != pro.ele_id);

                    that.clearGridLayer(pro);
                    that.removeLayer(pro);
                } else {
					if(pro.isrise&& pro.isrise == "true"){
						$(".product-szyb-list li.active").click();
					}else{
						$(this).siblings('li.active').click();
					}
                    let modeType = $(".product-szyb-tab li.active").data('model').fullname;
                    if (modeType === 'CMA-MESO6') {
                        that.delAllLayer();
                    }
                    
                    $(this).addClass("active").siblings().removeClass('active');
                    $(this).closest('.product-item').siblings().find('.product-pic-tab li').removeClass("active");

                    if (pro.fun && pro.ele_id != 'CAPE') { //若有自己的函数，则执行
						$('.product-pic-tab td.active').removeClass('active');
                        var fun = eval(pro.fun);
                        if ($.isFunction(fun)) {
                            fun($(this));
                        } else {
                            alert("请检查该要素的函数配置");
                        }
                        return;
                    }
                    if (pro.interval) {
                        $(".product-szyb-interval li").addClass('disabled');
                        $(".product-szyb-interval li[interval=" + pro.interval + "]").addClass('active').removeClass('disabled').siblings().removeClass('active');
                    }
                    that.selectedPro.push(pro);

                    var proInfo = that.getProInfo(pro);
                    // 增加产品图层
                    that.addLayerManage(proInfo);

                    that.getModelGridData(proInfo);
                }
            }).on('click', 'td', function () {
                var pro = $(this).data('pro');
                if (!pro) return;
                $("#modal_product_pic").remove();
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");

                    that.selectedPro = that.selectedPro.filter(item => item.ele_id != pro.ele_id);
                    that.clearGridLayer(pro);
                    that.removeLayer(pro);
                    that.relatedPro(pro, false);
                } else {
                    var prev = $(this).siblings('td.active');
                    if (prev.length > 0) {
                        prev.removeClass('active');
                        that.removeLayer(prev.data('pro'));
                        that.clearGridLayer(prev.data('pro'));
                    }

                    if (pro.fun) { //若有自己的函数，则执行
						$('.product-pic-tab li.active').removeClass('active');
                        var fun = eval(pro.fun);
						var prev = $(this).parent().parent().find('td.active');
						prev.removeClass('active');
						$(this).addClass('active');
                        if ($.isFunction(fun)) {
                            fun($(this));
                        } else {
                            alert("请检查该要素的函数配置");
                        }
                        return;
                    }
					$(this).addClass('active');
					
                    if (pro.interval) {
                        $(".product-szyb-interval li").addClass('disabled');
                        $(".product-szyb-interval li[interval=" + pro.interval + "]").addClass('active').removeClass('disabled').siblings().removeClass('active');
                    }

                    that.selectedPro.push(pro);

                    var proInfo = that.getProInfo(pro);
                    // 增加产品图层
                    that.addLayerManage(proInfo);
                    that.getModelGridData(proInfo);
                    that.relatedPro(pro, true);
                }
            })
            // 预报时间间隔
            $(".product-szyb-interval").delegate('li', 'click', function () {
                if ($(this).hasClass('disabled')) return;
                $(this).addClass("active").siblings().removeClass("active");
                var interval = Number($(this).attr('interval')) * 60;
                if (that.playList) {
                    that.playList.init({
                        timeInterval: interval
                    });
                }
                if ($("#modal_product_pic").length > 0) {
                    productPic.initProduct(0)
                }
                that.getMultiGridData();
            })
            // 最近起报时间
            $(".product-szyb-datechange").delegate('li', 'click', function () {
                $(this).addClass("active").siblings().removeClass("active");
                var time = $(this).data('time');
                $(".product-szyb-datepicker #date").IDatePicker().setVal(time);
                if (that.playList) {
                    that.playList.init({
                        curDate: time
                    });
                }
                if ($("#modal_product_pic").length > 0) {
                    productPic.initProduct(0)
                }
                that.getMultiGridData();
            })
            $('.product-szyb-datepicker').off('click').on('click', '.btn-forward', function (e) { // 日期向前
                e.stopPropagation();
                $(".product-szyb-datepicker #date").IDatePicker().toForward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
                if ($("#modal_product_pic").length > 0) {
                    productPic.initProduct(0)
                }
            }).on('click', '.btn-backward', function (e) { // 日期向后
                e.stopPropagation();
                $(".product-szyb-datepicker #date").IDatePicker().toBackward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
                if ($("#modal_product_pic").length > 0) {
                    productPic.initProduct(0)
                }
            }).on('click', ".btn-newest", function (e) { // 最新
                e.stopPropagation();
                $(".product-szyb-datepicker #date").IDatePicker().toNewest();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
                if ($("#modal_product_pic").length > 0) {
                    productPic.initProduct(0)
                }
            });

            //系统识别-下载
            $('.product-szyb-list').on('click', '.product-szyb-download',function () {
                that.dealDataDownDataFun();
            });

            if($("#userInfo").data("isMatchuser")){
                $(".product-szyb-tab li:eq(4)").click();
            }else{
                $(".product-szyb-tab li").first().click();
            }
            
        },
        initStamp: function ($dom) {
            $("#modal_product_pic,#modal_modelMap,#modal_point_pro,#modal_line_pro").remove();
            let _this = $dom,
                isCheck = $dom.hasClass("active");
            //把数值预报弹框固定在左上放
            $("#modal_szyb").css({ "left": $("#childMenu").width() + 10 + "px", "top": "50px" });
            CafeJS.ModalBoxClose("modelContrast");
            if (!isCheck) {
                CafeJS.ModalBoxClose("stamp");
                CafeJS.ModalBoxClose("bigStampMapPopUp");
                return;
            }
            CafeJS.ModalBox({
                id: "stamp",
                container: 'cafe-busis-container',
                title: "邮票图",
                width: $("body").width() - $("#modal_szyb").width() - $("#childMenu").width() - 30,
                height: 750,
                m_top: $("#modal_szyb").css("top"),
                m_left: $("#modal_szyb").width() + $("#childMenu").width() + 10,
                url: szyb.router.initStampPath,
                closed: function () {
                    _this.removeClass("active");
                }
            });

        },
        // 模式探空图
        initModelMap: function ($dom) {
            $("#modal_product_pic,#modal_stamp,#modal_point_pro,#modal_line_pro").remove();
            let _this = $dom,
                isCheck = $dom.hasClass("active");
            if (!isCheck) {
                CafeJS.ModalBoxClose("modelMap");
                return;
            }
            CafeJS.ModalBox({
                id: "modelMap",
                container: 'cafe-busis-container',
                title: "模式探空图",
                width: 1200,
                height: 750,
                m_top: $("#modal_szyb").css("top"),
                m_left: $("#modal_szyb").width() + $("#childMenu").width() + 20,
                url: szyb.router.initModelMapPath,
                closed: function () {
                    _this.removeClass("active");
                }
            });
        },
        initModelContrast: function ($dom) {
            let _this = $dom,
                isCheck = $dom.hasClass("active");
            if (isCheck) {
                _this.removeClass("active");
                CafeJS.ModalBoxClose("modelContrast");
                CafeJS.ModalBoxClose("bigModelContrastMapPopUp");
                return;
            }
            $dom.addClass("active");

            //把数值预报弹框固定在左上放
            CafeJS.ModalBoxClose("modelContrast");
            CafeJS.ModalBoxClose("bigModelContrastMapPopUp");
            CafeJS.ModalBoxClose("stamp");
            CafeJS.ModalBoxClose("bigStampMapPopUp");

            CafeJS.ModalBox({
                id: "modelContrast",
                container: 'cafe-busis-container',
                title: "模式对比",
                width: $("body").width() - $("#modal_szyb").width() - $("#childMenu").width() - 30,
                height: 750,
                m_top: $("#modal_szyb").css("top"),
                m_left: $("#modal_szyb").width() + $("#childMenu").width() + 10,
                url: szyb.router.initModelContrastPath,
                closed: function () {
                    _this.removeClass("active");
                }
            });

        },
        queryGridDataFormRSMin(params) {
            let that = this;
            $.ajax({
                url: that.router.queryGridDataFormRSMin,
                type: 'GET',
                dataType: 'json',
                async: false,
                data: {
                    element: params.element,
                    foreTime: params.foreTime
                }
            }).done(function (res) {
                if (res.code === 200 && res.data) {
                    that.currentSelectTime = '';
                    $('#tsfcSelect').empty().append('<option value="" disabled selected>请选择</option>');
                    $('#usfcSelect').empty().append('<option value="" disabled selected>请选择</option>');
                    $('#apcpSelect').empty().append('<option value="" disabled selected>请选择</option>');
                    let $select = $(`#${params.selectId}`).empty();
                    ['', ...res.data].forEach((el, index) => {
                        let $option = null;
                        if (index === 0) {
                            $option = $(`<option value="${el}" disabled selected>请选择</option>`);
                        } else {
                            $option = $(`<option value="${el}">${el}</option>`);
                        }
                        $select.append($option);
                    });
                } else {
                    console.error('queryGridDataFormRSMin error');
                }
            }).always(function ( jqXHR, textStatus ) {
                loading.remove();
            });
        },
        queryGridDataFormRS(params) {
            let that = this;
            
            let { selectId, ...o } = this.currentSelectEle;
            params = {
                ...o,
                time: this.currentSelectTime
            }
            CafeJS.ajax({
                url: that.router.queryGridDataFormRS,
                params: params,
                type: "GET",
                success: function (e) {
                    loading.remove();
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(that.currentPro);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, that.currentPro);
                }
            });
        },
    }
    if (typeof call === 'function') {
        CafeJS.szyb = szyb;
        call(szyb);
    }
    window.szyb = szyb;
})(function (szyb) {
    CafeJS.models(['ajax', 'legentconfig', 'legentpicker', 'timeLine2'], function () {
        szyb.init();
    });
});
